 //
// chat_message.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef CHAT_MESSAGE_HPP
#define CHAT_MESSAGE_HPP

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;

class Packet
{
public:
	const static int HEAD_LENGTH=4;
	const static int MAX_BODY_LENGTH = 512;

	Packet():_buffer(new char[HEAD_LENGTH + MAX_BODY_LENGTH]),_body(_buffer+HEAD_LENGTH),_body_length(0){}

	void setBody(const char* p,int l)
	{
		memcpy(_body,p,l);
		_body_length=l;
		encode_header();
	}
	void setHeader(const char* p)
	{
		memcpy(_buffer,p,HEAD_LENGTH);
		decode_header();
	}

	char* getBuffer()
	{
		_buffer[HEAD_LENGTH+_body_length]='\0';	
		return _buffer;
	}
	char* getBody()
	{
		_body[_body_length]='\0';	
		return _buffer + HEAD_LENGTH;
	}
	
	int getBodyLength()const{return (int)_body_length;}

	int getBufferLength()const{return (int)(HEAD_LENGTH + _body_length);}

	bool decode_header()
	{
		using namespace std; // For strncat and atoi.
		char header[HEAD_LENGTH + 1] = "";
		strncat(header, _buffer, HEAD_LENGTH);
		_body_length = atoi(header);
		if ((_body_length > MAX_BODY_LENGTH)|_body_length==0)
		{
			cout<<"packet over weight, so set length = 8 ."<<endl;
			_body_length = 8;
			return false;
		}
		return true;
	}

	void encode_header()
	{
		using namespace std; // For sprintf and memcpy.
		char header[HEAD_LENGTH + 1] = "";
		sprintf(header, "%4d", _body_length);
		memcpy(_buffer, header, HEAD_LENGTH);
	}

private:
	char* _buffer;
	char* _body;
	size_t _body_length;
};

#endif // CHAT_MESSAGE_HPP

